using System;
using System.IO;
using System.Collections.Generic;
using System.Text;

namespace Lutos.Spider
{
    public class EmailInfoWriter
    {
        public EmailInfoWriter(string path)
        {
            this.path = path;
        }

        private string path;

        private DateTime lastHour;
        private StreamWriter sw;
        private Dictionary<string, object> dict = new Dictionary<string, object>();
        public bool Add(string email)
        {
            email = email.Trim().ToLower();
            lock(this)
            {
                if (dict.ContainsKey(email))
                {
                    return true;
                }
                DateTime now = DateTime.Now;
                try
                {
                    if (sw == null)
                    {
                        sw = new StreamWriter(string.Format("{0}{1}.txt", path, now.ToShortDateString()), true);
                    }
                    else if (lastHour.Year != now.Year
                            || lastHour.Month != now.Month
                            || lastHour.Day != now.Day
                            || lastHour.Hour != now.Hour)
                    {
                        lastHour = now;
                        sw.Close();
                        sw = new StreamWriter(string.Format("{0}{1}.txt", path, now.ToShortDateString()), true);
                    }
                    sw.WriteLine(email);
                }
                catch
                {
                    return false;
                }
                dict.Add(email,null);
                return true;
            }
        }

        public void Close()
        {
            if(sw != null)
            {
                sw.Close();
            }
        }
    }
}
